/***********************************************************************
 * BinTrotter : BitTorrent library/client for the Android operating system.
 *  
 * Copyright (C) 2009, Christopher David Stones (chris.stones@gmail.com)
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 ***********************************************************************/

package org.bintrotter.apeer.receivestates;

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.SocketChannel;
import org.bintrotter.apeer.Peer;

public class PieceBlock implements ReceiveState {

	private Peer m_peer;
	private SocketChannel sc;
	private MappedByteBuffer[] bb;
	
	private int index;
	private int begin;
	private int length;
	private int bytesReceived;
	
	public PieceBlock(Peer peer) {
		
		m_peer = peer;
		sc = null;
		bb = null;
	}
	
	@Override
	public void reset() {
		
		bytesReceived = 0;
		index = ((PieceIndex)(m_peer.get(States.PIECE_INDEX))).index();
		begin = ((PieceBegin)(m_peer.get(States.PIECE_BEGIN))).begin();
		length =((MessageLength)(m_peer.get(States.LENGTH))).length()-9;
		sc = m_peer.channel();
		try {
			bb = m_peer.mmap(new org.bintrotter.apeer.Request(index,begin,length));
		} catch (IOException e) {

			bb = null;
			
		}
	}

	@Override
	public States update() {
		
		if(bb == null)
			return States.SHUTDOWN; // mmap failed !!!!
		
		
		try {

			long readBytes = sc.read(bb);
			
			bytesReceived += readBytes;
			
			if(bb[bb.length-1].hasRemaining() == false) {
			
				for(int i=0;i<bb.length;++i)
					bb[i]=null;
				bb = null;
				
				m_peer.inBlockComplete(index,begin,length);
				return States.LENGTH;
			}
			
		} catch (IOException e) {
			
			return States.SHUTDOWN;
		}
		
		return States.PIECE_BLOCK;
	}

}
